import React from 'react';
import ReactDOM from 'react-dom';
import {List, Toast,Button} from 'antd-mobile';
import mirror, {actions, connect} from 'mirrorx';
import {getCertiTypeEnum, getGenderEnum, getRelationEnum, getSA, getCoveragePeriod, getPaymentPeriod, getPayMode, getBenefitPeriod} from '../product/staticData';
import { createForm } from 'rc-form';
import RowInput from '../../component/Item/Input';
import RowSelect from '../../component/Item/Select';
import RowDate from '../../component/Item/DatePicker';
import Factor from '../../component/factor';
import Job from '../product/job';
import RiskNotice from '../product/riskNotice';


 function InsurantRender({insurantInfo,onChangeInsurant,factorInfo,onChangeJob,onChangeFactor,index,deleteInsurant}){
    const Lang = window.LangMessage ||{};
    
    return(<div>                
        <List>
            <RowSelect label={Lang.relation_with_holder || "與投保人關係"}  index={index}  name="relation" value={insurantInfo.relation} data={getRelationEnum()} callback={onChangeInsurant} />
            <RowInput label={Lang.name || "姓名"} name="insurantName" index={index} value={insurantInfo.insurantName} callback={onChangeInsurant} />
            <RowSelect label={Lang.certi_type || "證件類型"} name="insurantCertType" index={index} value={insurantInfo.insurantCertType} data={getCertiTypeEnum(1)} callback={onChangeInsurant} />
            <RowInput label={Lang.certi_no || "證件號碼"} name="insurantCertNo" index={index} value={insurantInfo.insurantCertNo} callback={onChangeInsurant} />                 
            <RowInput label={Lang.phone_no || "手機號碼"} type="phone" index={index} name="insurantMobile" value={insurantInfo.insurantMobile} callback={onChangeInsurant} />
        </List>                               
        {/* <Factor index={index} callback={onChangeFactor} {...factorInfo} type={T.urlQuery('goodId')} /> */}
    </div>); 
}


class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            applicantInfo: {
                applicantCertType: 'SHENFENZHENG',
            },  // 投保人信息
            // insurantInfo: {
            //     insurantCertType: 'SHENFENZHENG'
            // },   // 被保人信息
            insurants:[{
               insurantInfo:{insurantCertType: 'SHENFENZHENG',ensurePlanId: T.urlQuery('planId')},
               factorInfo:{}
            }], //多个被保人
            factorInfo: {},     // 保费试算因子信息
            totalAmount:0
        };

        this.goodId = T.urlQuery('goodId')
        this.channelGoodId = T.urlQuery('channelGoodId')
        this.planId = T.urlQuery('planId')
    }

    componentDidMount() {
        let initPrice = T.cookie.get('amount_' + this.goodId)
        Object.assign(this.state.insurants[0].insurantInfo,{insurantPremium:initPrice});
        this.calculateAmount();                     
        this.setState({insurants: this.state.insurants})       
    }

    onChangeApplicant = (obj,index) => {
        if(obj.hasOwnProperty('applicantCertNo')){
            var a = this.isIdCard(Object.values(obj)[0])
            if( Object.prototype.toString.call(a) == "[object Object]" ){
                Object.assign(this.state.applicantInfo, {
                    applicantBirthday: new Date(a.birthday).getTime(),
                    applicantGender: a.genderCode
                })
                this.setState({applicantInfo: this.state.applicantInfo})
            }
        }
        Object.assign(this.state.applicantInfo, obj)
        this.setState({applicantInfo: this.state.applicantInfo})
    }

    onChangeInsurant = (obj,index) => {       
        if(obj.relation == 'SELF'){ //与投保人关系是本人
            const {applicantName, applicantCertType, applicantCertNo, applicantBirthday,
                applicantGender, applicantMobile, applicantEmail} = this.state.applicantInfo;
            Object.assign(this.state.insurants[index].insurantInfo, {
                insurantName: applicantName,
                insurantCertType: applicantCertType,
                insurantCertNo: applicantCertNo,
                insurantMobile: applicantMobile,
                insurantEmail: applicantEmail,
            })
            this.onChangeFactor({
                birthday: applicantBirthday,
                gender: applicantGender
            },index);
        }
        if(obj.hasOwnProperty('insurantCertNo')){
            var a = this.isIdCard(Object.values(obj)[0])
            if( Object.prototype.toString.call(a) == "[object Object]" ){
                Object.assign(this.state.insurants[index].factorInfo, {
                    birthday: new Date(a.birthday).getTime(),
                    gender: a.genderCode
                })
                this.onChangeFactor(this.state.insurants[index].factorInfo,index);
            }
        }
        Object.assign(this.state.insurants[index].insurantInfo, obj)
        this.setState({insurants: this.state.insurants})
    }

    onChangeFactor = (obj,index) => {       
        if(obj.birthday){
            Object.assign(this.state.insurants[index].insurantInfo, {insurantBirthday:obj.birthday});
        }
        if(obj.gender){
            Object.assign(this.state.insurants[index].insurantInfo, {insurantGender:obj.gender})
        }
        Object.assign(this.state.insurants[index].factorInfo, obj)
        if(T.urlQuery('goodId') == '13' || T.urlQuery('goodId') == '14'){
            Object.assign(this.state.insurants[index].factorInfo, {payFrequencyType: "SINGLE"})
        }
        this.setState({factorInfo: this.state.insurants[index].factorInfo})
        let params = [{
            "bizTopic": "PREMIUM",
            "factorParams": this.state.insurants[index].factorInfo,
            "id": T.urlQuery('planId') // 计划id
        }]; 


        return
        T.fetch({ //保费试算
            url:'/cal/premium/amount.json',
            data:params
        }).then((res)=>{
            if(res.success){
                Object.assign(this.state.insurants[index].insurantInfo,{insurantPremium:res.value[0].calResp && res.value[0].calResp.calValue});
                this.calculateAmount();                     
                this.setState({insurants: this.state.insurants})
            }
        })
    }

    calculateAmount = ()=>{ //计算多个被保人的保费
        let totalAmount = 0;
        for(var i = 0; i < this.state.insurants.length; i++){
            if(this.state.insurants[i].insurantInfo.insurantPremium){
                totalAmount = totalAmount + Number(this.state.insurants[i].insurantInfo.insurantPremium);
            }
        }
        this.setState({totalAmount:totalAmount});
    }

    onChangeJob = (obj) => {
        this.setState(obj);
    }

    onChangeRiskNotice = (obj) => {
        this.setState(obj)
    }

    isIdCard = (card) => {
        if (!card) return true;
        var num = card.toUpperCase();
        //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X。
        if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))) {
            return false;
        }
        //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
        //下面分别分析出生日期和校验位
        var len, re;
        var birthday,genderCode;
        len = num.length;
        if (len == 15) {

            //获取出生日期
            birthday = '19' + card.substring(6, 8) + "-" + card.substring(8, 10) + "-" + card.substring(10, 12);
            //获取性别
            genderCode = parseInt(card.substr(14, 1)) % 2 == 1 ? 'MALE' : 'FMAIL';

            re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
            var arrSplit = num.match(re);

            //检查生日日期是否正确
            var dtmBirth = new Date('19' + arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4]);
            var bGoodDay;
            bGoodDay = (dtmBirth.getYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]));
            if (!bGoodDay) {
            return false;
            } else {
            //将15位身份证转成18位
            //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
            var valnum;
            var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            var nTemp = 0,
                i;

            num = num.substr(0, 6) + '19' + num.substr(6, num.length - 6);
            for (i = 0; i < 17; i++) {
                nTemp += num.substr(i, 1) * arrInt[i];
            }
            num += arrCh[nTemp % 11];
            }
        } else if (len == 18) {

            //获取出生日期
            birthday = card.substring(6, 10) + "-" + card.substring(10, 12) + "-" + card.substring(12, 14);
            //获取性别
            genderCode = parseInt(card.substr(16, 1)) % 2 == 1 ? 'MALE' : 'FMAIL';

            re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
            var arrSplit = num.match(re);

            //检查生日日期是否正确
            var dtmBirth = new Date(arrSplit[2] + "/" + arrSplit[3] + "/" + arrSplit[4]);
            var bGoodDay;
            bGoodDay = (dtmBirth.getFullYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]));
            if (!bGoodDay) {
            return false;
            } else {
            //检验18位身份证的校验码是否正确。
            //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
            var valnum;
            var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            var nTemp = 0,
                i;
            for (i = 0; i < 17; i++) {
                nTemp += num.substr(i, 1) * arrInt[i];
            }
            valnum = arrCh[nTemp % 11];
            if (valnum != num.substr(17, 1)) {
                return false;
            }
            }
        }
        return {
            birthday: birthday,
            genderCode: genderCode
        }
    }

    submitAction = () => {
        const Lang = window.LangMessage ||{};
        let tipsResult = JSON.parse(sessionStorage.getItem("tipsResult"));
        console.log('tipsResult...',tipsResult);
        sessionStorage.setItem("Insure",  JSON.stringify(this.state.applicantInfo));        
        let ensurePersons = [];
        for(var i = 0;i < this.state.insurants.length; i++){
            this.state.insurants[i].insurantInfo.insurantMobile = this.state.insurants[i].insurantInfo.insurantMobile ||""
            this.state.insurants[i].insurantInfo.insurantMobile = this.state.insurants[i].insurantInfo.insurantMobile.replace(/ /g, "");
            if( T.urlQuery('goodId') == '15' ){
            this.state.insurants[i].insurantInfo.insureOccupation = this.state.insureOccupation;
            this.state.insurants[i].insurantInfo.damageLevel = this.state.damageLevel;            
            // param.ensurePersons[0].insurePayTerm = this.state.factorInfo.paymentPeriod;
            this.state.insurants[i].insurantInfo.paymentFrequency = this.state.insurants[i].factorInfo.payFrequencyType;
            }else if( T.urlQuery('goodId') == '14' ){
                
            }else if( T.urlQuery('goodId') == '13' ){
                this.state.insurants[i].insurantInfo.insureCoveragePeriod = this.state.insurants[i].factorInfo.coveragePeriod;
            }else if( T.urlQuery('goodId') == '10' ){
                this.state.insurants[i].insurantInfo.insurance = this.state.insurants[i].factorInfo.socialInsurance;
            }else if( T.urlQuery('goodId') == '20' ){
                this.state.insurants[i].insurantInfo.insurance = this.state.insurants[i].factorInfo.socialInsurance;
            }else if( T.urlQuery('goodId') == '21' || T.urlQuery('goodId') == '112001' ){
                this.state.insurants[i].insurantInfo.insurance = this.state.insurants[i].factorInfo.socialInsurance;
            }else if( T.urlQuery('goodId') == '25' ){
               this.state.insurants[i].insurantInfo.paymentFrequency = this.state.insurants[i].factorInfo.payFrequencyType;
            }else if( T.urlQuery('goodId') == '1' ){
                this.state.insurants[i].insurantInfo.insurance = this.state.insurants[i].factorInfo.socialInsurance;
            }else if( T.urlQuery('goodId') == '2' ){
                this.state.insurants[i].insurantInfo.insurePayTerm = this.state.insurants[i].factorInfo.paymentPeriod;//繳費年限
                this.state.insurants[i].insurantInfo.insureNum = this.state.insurants[i].factorInfo.unit;//份数
            }else if( T.urlQuery('goodId') == '9' ){
                this.state.insurants[i].insurantInfo.insurePayTerm = this.state.insurants[i].factorInfo.paymentPeriod;//繳費年限
                this.state.insurants[i].insurantInfo.insureCoveragePeriod = this.state.insurants[i].factorInfo.coveragePeriod;//保障期間
                this.state.insurants[i].insurantInfo.insureNum = this.state.insurants[i].factorInfo.unit;//份数
                this.state.insurants[i].insurantInfo.insureOccupation = this.state.insurants[i].factorInfo.occupation;//职业类别
            }else if( T.urlQuery('goodId') == '12' ){
                this.state.insurants[i].insurantInfo.insurePayTerm = this.state.insurants[i].factorInfo.paymentPeriod;//繳費年限
                this.state.insurants[i].insurantInfo.insureCoveragePeriod = this.state.insurants[i].factorInfo.coveragePeriod;//保障期間
                this.state.insurants[i].insurantInfo.paymentFrequency = this.state.insurants[i].factorInfo.payFrequencyType;//繳別
            }
            else if( T.urlQuery('goodId') == '42003' ){
                this.state.insurants[i].insurantInfo.paymentFrequency = this.state.insurants[i].factorInfo.payFrequencyType;//繳別
            }
            ensurePersons.push(this.state.insurants[i].insurantInfo);
        }
        let param = {
            ...this.state.applicantInfo,
            ensurePersons:ensurePersons,
            goodsId: T.urlQuery('goodId'),
            campaignId: T.urlQuery('campaignId'),
            tipsResult,
        };
        param.applicantMobile = param.applicantMobile && param.applicantMobile.replace(/ /g, "");
        if( T.urlQuery('goodId') == '9' ){
            param.orderType = 'FAMILY';
        }else{
            param.orderType = 'COMMON';
        }
        if( T.urlQuery('goodId') == '15' ){           
           param.bankCardId = this.state.bankCardId;
        }

        console.log(param)

        if(!this.state.showRiskNotice){
            T.showError(Lang.check_agree_insure_protcol || "请勾选同意投保须知");
        }else{
            this.requestSubmit(param)
        }

    }

    resetParam(data){
        let initPrice = T.cookie.get('amount_' + this.goodId)
        let insurant = data.ensurePersons[0]
        let tempParam = {
            "channelGoodsId":this.channelGoodId,
            //"partnerId":"12001",
            "orderSource":"1",
            "orderAmount":initPrice,
            "currencyUnit":"1",
            "payType":"1",
            "payPassword":"123456",
            "subject":"asd",
            "userIp":"223.232.23.2",
            "callbackUrl":"",
            "planId":this.planId,

            holderName:data.applicantName,
            holderCertType:data.applicantCertType,
            holderCertNo:data.applicantCertNo,
            holderMobile:data.applicantMobile,
            insurantName:insurant.insurantName,
            insurantCertType:insurant.insurantCertType,
            insurantCertNo:insurant.insurantCertNo,
            insurantMobile:insurant.insurantMobile
        }
        return tempParam
    }

    requestSubmit = (param) => {
        let initPrice = T.cookie.get('amount_' + this.goodId)
        param = this.resetParam(param)
        
        T.fetchFusion({ 
            url:'/pay/prePay',
            loading:true,
            data:param
        }).then((res)=>{
            if(res.success){      
                let orderNo = res.value.orderNo   ||'A33221343232'      
              
                actions.routing.push({
                    pathname: 'pay-poc',
                    search: `?id=${orderNo}&price=${initPrice}`
                })
            }
        })
    }

    addInsurant = ()=>{ //添加被保人        
        let insurants = this.state.insurants;
        insurants.push(
            {
               insurantInfo:{insurantCertType: 'SHENFENZHENG',ensurePlanId: T.urlQuery('planId')},
               factorInfo:{}
            }
        );
        this.setState(insurants)

    }

    deleteInsurant = (index)=>{ //删除被保人        
        let insurants = this.state.insurants;
        if(insurants.length <= 1){
            T.showError("至少要有一个被保人");
            return;
        }
        insurants.splice(index,1);
        this.setState(insurants);
        this.calculateAmount();
    }

    render() {
        let {applicantInfo,factorInfo, goodId,insurants} = this.state;
        const Lang = window.LangMessage ||{};        
        
        return (
            <div className="insure">
                <div className="title">{Lang.holder_info || "投保人信息"}</div>
                <div>
                    <List>
                        <RowInput label={Lang.name || "姓名"} name="applicantName" value={applicantInfo.applicantName} callback={this.onChangeApplicant} />
                        <RowSelect label={Lang.certi_type || "證件類型"} name="applicantCertType" value={applicantInfo.applicantCertType} data={getCertiTypeEnum(1)} callback={this.onChangeApplicant} />
                        <RowInput label={Lang.certi_no || "證件號碼"} name="applicantCertNo" value={applicantInfo.applicantCertNo} callback={this.onChangeApplicant} />
                        <RowInput label={Lang.phone_no || "手機號碼"} type="phone" name="applicantMobile" value={applicantInfo.applicantMobile} callback={this.onChangeApplicant} />
                    </List>
                </div>
                <div className="title">{Lang.insurant_info || "被保人信息"}</div>     
                 {insurants.map((item,index)=>
                    <div key={index}>
                        <InsurantRender index={index} insurantInfo={item.insurantInfo} deleteInsurant={this.deleteInsurant}
                        onChangeInsurant={this.onChangeInsurant} factorInfo={item.factorInfo} 
                        onChangeJob={this.onChangeJob} onChangeFactor={this.onChangeFactor}/>                           
                    </div>                     
                 )} 
                
                 <div className="clearfix"></div>
                
                <RiskNotice callback={this.onChangeRiskNotice}  goodId={T.urlQuery('goodId')} className="grab"/>
                <div className="footer">
                    <div className="footer-left">
                        <a className="f38 fc6 tac color-price">&nbsp;&nbsp;<span className="f30"></span><span id="totalMoney">{this.state.totalAmount || 0}</span></a>
                    </div>
                    <div className="footer-right">
                        <a href="javascript:;"  className="f32 fcw diy_background-grab" id="applyBtn" onClick={this.submitAction}>{Lang.insure_right_now || "立即投保"}</a>
                    </div>
                </div>
            </div>
        )
    }
}

export default App;